package com.base.component.ai.platform.prompt;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.base.component.ai.agent.utils.PromptChatUtils;
import com.base.component.ai.platform.core.bo.common.ChatCompletionsBO;
import com.base.component.ai.platform.core.converter.MessageRoleEnum;
import com.base.core.head.dto.ai.MessageTextDTO;
import com.gitee.magic.core.utils.StringUtils;

@Service
public class PromptTextRawService extends PromptBaseRawService<MessageTextDTO> {
	
	public PromptTextRawService() {
		super(MessageTextDTO.class);
	}
	
	@Autowired
	private PromptTemplateService<MessageTextDTO> promptTemplateService;

	public ChatCompletionsBO<MessageTextDTO> getChatCompletionsParam(String code,String language,Map<String,Object> param) {
		ChatCompletionsBO<MessageTextDTO> ccb=super.getChatCompletionsParam(code, language, param);
		List<MessageTextDTO> messages=new ArrayList<>();
		if(!StringUtils.isEmpty(ccb.getSystemPrompt())) {
			MessageTextDTO message=new MessageTextDTO();
			message.setRole(MessageRoleEnum.SYSTEM.name().toLowerCase());
			message.setContent(ccb.getSystemPrompt());
			messages.add(message);
		}
		if(!StringUtils.isEmpty(ccb.getUserPrompt())) {
			MessageTextDTO message=new MessageTextDTO();
			message.setRole(MessageRoleEnum.USER.name().toLowerCase());
			message.setContent(ccb.getUserPrompt());
			messages.add(message);
		}
		ccb.setMessages(messages);
		return ccb;
	}

	public void executeStream(String code,String language,Map<String,Object> param,Consumer<String> frameConsumer,Consumer<String> successedConsumer) {
		ChatCompletionsBO<MessageTextDTO> ccb=getChatCompletionsParam(code, language,param);
		StringBuilder data = new StringBuilder();
		promptTemplateService.execute(ccb,getPrototype(), (s) -> {
			if (!StringUtils.isEmpty(s)) {
				data.append(s);
				PromptChatUtils.handleTextFrame(data, frameConsumer);
			}
		}, (s) -> {
			if (!data.isEmpty()) {
				successedConsumer.accept(data.toString());
			}
		});
	}
	
}
